package hgz.stu.review.ruijie.enviroment;

import java.util.Properties;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.core.io.support.PropertiesLoaderUtils;

public class SkyEngineEnv {

	private static final Logger LOGGER = LoggerFactory.getLogger(SkyEngineEnv.class);

	private static final SkyEngineEnvType DEFAULT_TYPE = SkyEngineEnvType.DEV;

	private static final String ENV_KEY = "skyengine.active.env";

	private static final String DEFAULT_ENV_FILE_NAME = "config/env.properties";

	/**
	 * 当前运行环境
	 */
	private static SkyEngineEnvType type = DEFAULT_TYPE;

	static {
		initEnvironment();
	}

	/**
	 * 
	 * 初始化环境类型 1.优先从JVM中获取运行环境类型，如果获取成功，则直接返回， 2.在1失败的情况下,改从配置文件中获取运行环境类型,如果成功则返回
	 * 3.如果从配置文件中获取失败，则返回默认的配置dev
	 */
	protected static void initEnvironment() {

		type = getSkyEngineEnvTypeFromJvm();
		if (SkyEngineEnvType.FAIL != type) {
			return;
		}
		type = getSkyEngineEnvTypeFromConfigFile();

		if (SkyEngineEnvType.FAIL != type) {
			return;
		}

		type = DEFAULT_TYPE;
	}

	/**
	 * 从jvm环境中获取运行环境 逻辑： 
	 * System.getProperty() 方法有可能抛异常，记录异常，并返回SkyEngineEnvType.FAIL 
	 * 
	 * @return
	 */
	protected static SkyEngineEnvType getSkyEngineEnvTypeFromJvm() {
		try {
			String jvmEnv = System.getProperty(ENV_KEY);
			return SkyEngineEnvType.convert(jvmEnv);
		} catch (Exception e) {
			LOGGER.error("从jvm中获取运行配置", e);
		}
		return SkyEngineEnvType.FAIL;

	}

	/**
	 * 从配置文件中获取运行环境 
	 * loadAllProperties()方法可能抛异常，如果抛异常，直接返回SkyEngineEnvType.FAIL
	 * 
	 * @return
	 */
	protected static SkyEngineEnvType getSkyEngineEnvTypeFromConfigFile() {
		try {
			Properties properties = PropertiesLoaderUtils.loadAllProperties(DEFAULT_ENV_FILE_NAME);
			String activeEnv = properties.getProperty(ENV_KEY);
			return SkyEngineEnvType.convert(activeEnv);
		} catch (Exception e) {
			LOGGER.error("从配置文件 {} ", DEFAULT_ENV_FILE_NAME, e);
		}

		return SkyEngineEnvType.FAIL;
	}

	public static SkyEngineEnvType getType() {
		return type;
	}

}
